package com.fang.shirotestnoredis.shiro;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fang.shirotestnoredis.pojo.User;
import com.fang.shirotestnoredis.util.JWTUtil;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import java.util.HashSet;
import java.util.Set;

/**
 * 定义shiro框架：用户域
 */
public class UserRealm extends AuthorizingRealm {
    //Shiro框架的两个核心模块：认证和授权

    // @Autowired
    // private UserDao userDao;

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JWTToken;
    }


    /***
     * 权限认证
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //获取token
        String token = (String) authenticationToken.getCredentials();
        // //解密，获取userId
        // String userId = JWTUtil.getUserId(token);
        // System.out.println(userId);
        // String password = JWTUtil.getUserPassword(token);
        // System.out.println(password);
        // QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        // queryWrapper.eq("user_id",userId).eq("paswd",password);
        // User user = userDao.selectOne(queryWrapper);
        User user = new User();
        user.setID("123456");
        user.setUsername("admin");
        user.setPassword("admin");
        try {
            //通过认证后返回
            if (user != null && JWTUtil.verify(token)){
                return new SimpleAuthenticationInfo(token,token,this.getName());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     *授权处理：保存用户角色，这里主要保存管理员(1)和普通成员(0)的角色
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //拿到安全信息
        String userId = JWTUtil.getUserId(principalCollection.toString());
        // User user = userDao.selectById(userId);
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        Set<String> role = new HashSet<>();
        //记录当前登录用户的角色：0普通用户、1管理员
        // role.add(user.getUserAuthority()+"");
        role.add("root");
        authorizationInfo.setRoles(role);
        return authorizationInfo;
    }



}
